package cn.lhl.mvc;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

/**
 * Created by datou on 2017/3/15.
 */
public class ConfigurationManager {
    private ActionMapper actionMapper = new ActionMapper();
    public ConfigurationManager(){

    }

    public ActionMapper getActionMapper() {
        return actionMapper;
    }

    public void setActionMapper(ActionMapper actionMapper) {
        this.actionMapper = actionMapper;
    }

    public ConfigurationManager(String[] configer) throws DocumentException {

            config(configer);
    }



    public void config(String[] configer) throws DocumentException {
        if(configer==null){
            configer=new String[]{"datou.xml"};
        }
        for (String item : configer) {
            InputStream is = this.getClass().getResourceAsStream("/" + item);
            Document doc = new SAXReader().read(is);
            Element root = doc.getRootElement();
            Element actions = (Element) root.elements("actions").iterator().next();
            for (Iterator<Element> action = actions.elementIterator("action"); action.hasNext(); ) {
                Element actionnext = action.next();
                ActionMapping actiomMapping = new ActionMapping();
                actiomMapping.setActionName(actionnext.attributeValue("name"));
                if (actionnext.attributeValue("class") != null) {
                    actiomMapping.setClassName(actionnext.attributeValue("class"));
                }
                if (actionnext.attributeValue("method") != null) {
                    actiomMapping.setMethod(actionnext.attributeValue("method"));
                }
                for (Iterator<Element> result = actionnext.elementIterator("result"); result.hasNext(); ) {
                    Element resultnext = result.next();
                    ResultMapper resultMapper = new ResultMapper();
                    if (resultnext.attributeValue("name") != null) {
                        resultMapper.setResultName(resultnext.attributeValue("name"));
                    }
                    if (resultnext.attributeValue("type") != null) {
                        resultMapper.setResultType(resultnext.attributeValue("type"));
                    }
                    resultMapper.setResultPath(resultnext.getText());
                    actiomMapping.setResult(resultMapper);
                }
                actionMapper.setActiomMapping(actiomMapping);
            }

        }
    }
}
